package top.pengdong.dachuang.main.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @description:
 * @projectName: dachuang
 * @see: top.pengdong.dachuang.main.util
 * @author: pc
 * @createTime: 2022/3/11 11:47
 * @version: 1.0
 */

@Component
public class JwtTokenUtil {

	@Value("${jwt.secret}")
	private String secret;

	@Value("${jwt.expiration}")
	private Long expiration;

	/**
	 * 生成token
	 * @param userDetails
	 * @return
	 */
	public String generateToken(UserDetails userDetails) {
		return JWT.create()
				.setPayload("username", userDetails.getUsername())
				.setExpiresAt(new Date(System.currentTimeMillis() + expiration * 1000))
				.setKey(secret.getBytes())
				.sign();
	}

	/**
	 * 验证token
	 * @param token
	 * @return
	 */
	public boolean validate(String token) {
		try {
			return JWTUtil.verify(token, secret.getBytes(StandardCharsets.UTF_8))
					|| validateDate(token)
					|| validateAlgorithm(token);
		} catch (ValidateException e) {
			return false;
		}
	}

	/**
	 * 用户 token 过期验证
	 * @param token
	 * @return
	 */
	public boolean validateDate(String token) {
		try {
			JWTValidator.of(token).validateDate(DateUtil.date());
			return true;
		} catch (ValidateException e) {
			return false;
		}
	}

	/**
	 * 算法验证
	 * @param token
	 * @return
	 */
	public boolean validateAlgorithm(String token) {
		try {
			JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs512(secret.getBytes()));
			return true;
		} catch (ValidateException e) {
			return false;
		}
	}

	/**
	 * 获取用户名
	 * @param authToken
	 * @return
	 */
	public String getUserNameFromToken(String authToken) {
		String username;
		try {
			JWT jwt = JWTUtil.parseToken(authToken);
			username = (String) jwt.getPayload("username");
		} catch (Exception e) {
			username = null;
		}
		return username;
	}

	public static void main(String[] args) {
		String str = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InBlbmdzaGkiLCJleHAiOjE2NDcwNDg1Njl9.yO-iILWh1D5bJ_TAgcyDWwLG-m3dUM2ISBQAu7ZaKl8";
		JWT jwt = JWTUtil.parseToken(str);
		String username = (String) jwt.getPayload("username");
		System.out.println(username);

		String token = JWT.create()
				.setPayload("username", "pengshi")
				.setExpiresAt(new Date(System.currentTimeMillis() + 64800 * 1000))
				.setKey("da-chuang".getBytes())
				.sign();

		JWT jwt1 = JWTUtil.parseToken(token);
		System.out.println(token);
		String username1 = (String) jwt1.getPayload("username");
		System.out.println(username1);
	}
}
